package com.sinoglobal.ningxia.activity.amusement;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.ContentObserver;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKEvent;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.IBase;
import com.sinoglobal.ningxia.activity.amusement.AmusementDialog.AmusementDialogClickListener;
import com.sinoglobal.ningxia.beans.AmusementListVo;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.AbstractActivity;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.utils.LoctionUtil;

/**
 * @Title: AmuseMentMapActivity.java
 * @Package com.sinoglobal.ningxia.activity.amusement
 * @Description: TODO(地图模式)
 * @author czz
 * @date 2014-6-24 上午9:49:09
 */
public class AmuseMentMapActivity extends AbstractActivity implements IBase {
	private MapView mMapView;
	private double mLat1 = 39.90923;
	private double mLon1 = 116.397428;
	private BMapManager mBMapMan;
	private ImageButton mylocation_ibtn;
	private Drawable mark;
	private MyLocationOverlay myLocationOverlay; // 当前位置的Overlay
	private MapController mMapController;
	private ProgressDialog locationPd; // 定位的dialog
	private boolean flag = false;
	private boolean flag_isfirst = true;
	private LocationClient mLocationClient;// 定位的客户端
	private AmusementDialog dialog;
	private int info_num = 1; // 定位成功之后， 发送handler 的 what
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		titleView.setText(getString(R.string.Map_Mode));
		mBMapMan = new BMapManager(getApplication());
		mBMapMan.init(new MyGeneralListener());
		setContentView(R.layout.activity_amsuement_map);
		init();
		showListener();
		if (FilterRequirement.ENTERTAINMENT.equals(FilterRequirement.TYPE)
				|| FilterRequirement.CATE.equals(FilterRequirement.TYPE)) {
			obtainNearbyInfo();
		} else {
			getContentResolver()
					.registerContentObserver(
							Settings.Secure
									.getUriFor(Settings.System.LOCATION_PROVIDERS_ALLOWED),
							false, mGpsMonitor);
			locationPd = new ProgressDialog(this);
			locationPd.setMessage(getString(R.string.geting_location));
			// 初始化数据
			// 1、判断用户是否打开gps
			if (LoctionUtil.isOPen(this)) {
				// 去定位
				showLocaltion(true);
			} else {
				if (FlyApplication.isGpsFlag1) {
					String message = getString(R.string.please_openGps);
					dialog = new AmusementDialog(this, message, false);
					dialog.alertIvExpression.setVisibility(View.INVISIBLE);
					dialog.setAtdialogclick(new AmusementDialogClickListener() {
						@Override
						public void doConfirm() {
							flag = true;
							try {
								Intent intent = new Intent();
								flag = true;
								intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
								intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								startActivity(intent);
								dialog.cancel();
							} catch (Exception e) {
								String info = getString(R.string.gps_disabled);
								showShortToastMessage(info);
							}
						}

						@Override
						public void doCancel() {
							FlyApplication.isGpsFlag1 = false;
							showLocaltion(false);
							dialog.cancel();
						}
					});
					dialog.show();
				} else {
					showLocaltion(false);
				}

			}
		}
		// MyLocation();
		// 请求附近的数据
	}

	private final ContentObserver mGpsMonitor = new ContentObserver(null) {
		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			if (LoctionUtil.isOPen(AmuseMentMapActivity.this)) {
				dialog.dismiss();
				// 初始化数据

				if (flag_isfirst) {
					handler.sendEmptyMessage(3);
				}
			} else {
				// showShortToastMessage("GPS已经关闭!");
				handler.sendEmptyMessage(4);
			}
		}
	};
	private Handler handler = new Handler() {
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			switch(msg.what){
			case 1:
				obtainNearbyInfo();
				break;
			case 3:
				showShortToastMessage(getString(R.string.gps_opened));
				showLocaltion(true);
				break;
			case 4:
				showShortToastMessage(getString(R.string.gps_closed));
				break;
				default:
					break;
			}
		}
	};

	@Override
	protected void onRestart() {
		super.onRestart();
		if (flag) {
			if (!LoctionUtil.isOPen(this)) {
				showShortToastMessage(getString(R.string.gps_notOpen));
				showLocaltion(false);
			}
			flag = false;
		}
	}

	private void showLocaltion(boolean gpsIsOpen) {
		flag_isfirst = false;
		locationPd.show();
		mLocationClient = new LocationClient(AmuseMentMapActivity.this); // 声明LocationClient类
		MyLocationListener myListener = new MyLocationListener();
		mLocationClient.registerLocationListener(myListener); // 注册监听函数
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);// 设置定位模式
		option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02
		option.setScanSpan(5000);// 设置发起定位请求的间隔时间为5000ms
		option.setIsNeedAddress(true);// 返回的定位结果包含地址信息
		option.setNeedDeviceDirect(true);// 返回的定位结果包含手机机头的方向
		option.setOpenGps(gpsIsOpen);
		mLocationClient.setLocOption(option);
		mLocationClient.start();
	}

	class MyLocationListener implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;
			FlyApplication.latitude = String.valueOf(location.getLatitude());
			FlyApplication.longitude = String.valueOf(location.getLongitude());
			location.getCoorType();
			if (location.getLocType() == BDLocation.TypeGpsLocation) {
				// gps定位
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
				// 网络定位
				FlyApplication.addr = location.getProvince(); // 省份
			}
			// 1、定位成功之后关闭定位功能 -- 如果未成功就使用默认城市
			if (mLocationClient != null) {
				mLocationClient.stop();
			}
			locationPd.dismiss();
			handler.sendEmptyMessage(info_num);
		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
			FlyApplication.latitude = String.valueOf(poiLocation.getLatitude());
			FlyApplication.longitude = String.valueOf(poiLocation.getLongitude());
			if (poiLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
				FlyApplication.addr = poiLocation.getAddrStr();
			}

		}
	}

	private void obtainNearbyInfo() {
		mLat1 = Double.parseDouble(FlyApplication.latitude);
		mLon1 = Double.parseDouble(FlyApplication.longitude);
		// 得到mMapView的控制权,可以用它控制和驱动平移和缩放
		GeoPoint point = new GeoPoint((int) (mLat1 * 1E6), (int) (mLon1 * 1E6));
		// 用给定的经纬度构造一个GeoPoint，单位是微度 (度 * 1E6)
		mMapController.setCenter(point);// 设置地图中心点
		mMapController.setZoom(12);// 设置地图zoom级别
		mMapView.getController().enableClick(true);
		new ItktAsyncTaskWithDialog<Void, Void, AmusementListVo>(getString(R.string.loading_near_data),
				true, true) {

			@Override
			public AmusementListVo before(Void... params) throws Exception {
				return RemoteImpl.getInstance().getMapListfortype(
						FilterRequirement.TYPE, String.valueOf(0), String.valueOf(10));
			}

			@Override
			public void after(AmusementListVo result) {
				if (result != null) {
					if (Code.CODE_SUCCESS == result.getCode()) {
						if (FilterRequirement.ENTERTAINMENT.equals(FilterRequirement.TYPE)) {
							mark = getResources().getDrawable(
									R.drawable.img_map_icon_yule);
						} else if (FilterRequirement.CATE.equals(FilterRequirement.TYPE)) {
							mark = getResources().getDrawable(
									R.drawable.img_map_icon_meishi);
						} else if (FilterRequirement.AnJu.equals(FilterRequirement.TYPE)) {
							mark = getResources().getDrawable(
									R.drawable.img_map_icon_jiudian);
						}
						// 创建IteminizedOverlay
						MyOverlay itemOverlay = new MyOverlay(
								AmuseMentMapActivity.this, mark, mMapView,
								result);
						// 将IteminizedOverlay添加到MapView中
						mMapView.getOverlays().clear();
						mMapView.getOverlays().add(itemOverlay);
						for (int i = 0; i < result.getList().size(); i++) {
							// 用给定的经纬度构造GeoPoint，单位是微度 (度 * 1E6)
							double latitude =0.0;
							double longitude=0.0;
							try{
								 latitude = Double.parseDouble(result
										.getList().get(i).getLatitude());
								 longitude = Double.parseDouble(result
										.getList().get(i).getLongitude());
							}catch(Exception e){
								e.printStackTrace();
								latitude=0.0;
								longitude=0.0;
								
							}
							
							GeoPoint p1 = new GeoPoint((int) (latitude * 1E6),
									(int) (longitude * 1E6));
							// 用OverlayItem准备Overlay数据
							OverlayItem item1 = new OverlayItem(p1, "item1",
									"item1");
							// 现在所有准备工作已准备好，使用以下方法管理overlay.
							// 添加overlay,
							// 当批量添加Overlay时使用addItem(List<OverlayItem>)效率更高
							itemOverlay.addItem(item1);
						}
						myLocationOverlay = new MyLocationOverlay(mMapView);
						LocationData locData = new LocationData();
						// 手动将位置源置为天安门，在实际应用中，请使用百度定位SDK获取位置信息，要在SDK中显示一个位置，需要使用百度经纬度坐标（bd09ll）
						locData.latitude = Double
								.parseDouble(FlyApplication.latitude);
						locData.longitude = Double
								.parseDouble(FlyApplication.longitude);
						locData.direction = 2.0f;
						myLocationOverlay.setData(locData);
						mMapView.getOverlays().add(myLocationOverlay);
						mMapView.refresh();
					}
				}
			}

			@Override
			public void exception() {
			}
		}.execute();
	}

	// 常用事件监听，用来处理通常的网络错误，授权验证错误等
	class MyGeneralListener implements MKGeneralListener {
		@Override
		public void onGetNetworkState(int iError) {
			String info;
			switch(iError){
			case MKEvent.ERROR_NETWORK_CONNECT:
				info = getString(R.string.network_isError);
				showShortToastMessage(info);
				break;
			case MKEvent.ERROR_NETWORK_DATA:
				info = getString(R.string.please_input_SearchCondition);
				showShortToastMessage(info);
				break;
				default:
					break;
			}
		}

		@Override
		public void onGetPermissionState(int iError) {
			// 非零值表示key验证未通过
			// if (iError != 0) {
			// // 授权Key错误：
			// Toast.makeText(ShifuMapActivity.this,
			// "请在 DemoApplication.java文件输入正确的授权Key,并检查您的网络连接是否正常！error: " +
			// iError,
			// Toast.LENGTH_LONG).show();
			// } else {
			// Toast.makeText(ShifuMapActivity.this, "key认证成功",
			// Toast.LENGTH_LONG).show();
			// }
		}
	}

	@Override
	public void init() {
		mMapView = (MapView) findViewById(R.id.bmapsView);
		mylocation_ibtn = (ImageButton) findViewById(R.id.mylocation_ibtn);
		mMapView.setBuiltInZoomControls(false);
		mMapController = mMapView.getController();

	}

	// private void MyLocation() {
	//
	// mMapView.getController().animateTo(new GeoPoint((int) (locData.latitude *
	// 1e6), (int) (locData.longitude * 1e6)));
	// mMapView.refresh();
	// }
	@Override
	public void showListener() {
		mylocation_ibtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				GeoPoint point = new GeoPoint((int) (mLat1 * 1E6),
						(int) (mLon1 * 1E6));
				mMapController.setZoom(mMapView.getZoomLevel());// 设置地图zoom级别
				mMapController.animateTo(point);
				mMapView.getController().enableClick(true);
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mGpsMonitor != null) {
			// 注销 gps监听广播
			getContentResolver().unregisterContentObserver(mGpsMonitor);
		}
	}
}
